package app

import (
	"fmt"
	"gitee.com/mirzatsoft/wakit/config"
	"github.com/spf13/cobra"
)

var webCommand = &cobra.Command{
	Use:   "web",
	Short: "web command",
	Run: func(cmd *cobra.Command, args []string) {
		if err := config.Init(); err != nil {
			panic(err)
		}
		cfg := config.GetConfig()
		app, err := NewWebApp(cfg)
		if err != nil {
			panic(err)
		}

		if err := app.Start(); err != nil {
			panic(err)
		}
	},
}

func init() {
	root.AddCommand(webCommand)
}

type WebApp struct {
	ctx     *WebAppContext
	modules []Module
}

func NewWebApp(cfg *config.Config) (*WebApp, error) {
	ctx, err := NewContext(cfg)
	if err != nil {
		return nil, err
	}

	return &WebApp{
		ctx: ctx,
	}, nil
}

func (wa *WebApp) Register(mod Module) error {
	if err := mod.Init(wa.ctx); err != nil {
		return err
	}

	group := wa.ctx.Router.Group(mod.Name())
	mod.Routes(group)

	wa.modules = append(wa.modules, mod)
	return nil
}

func (wa *WebApp) Start() error {
	fmt.Println(wa)
	return wa.ctx.Router.Run(fmt.Sprintf(":%d", wa.ctx.Config.Web.Port))
}
